package com.ywu.standard.gateway.filter;

import com.ywu.boot.context.YwuContext;
import com.ywu.boot.context.YwuContextHolder;
import com.ywu.standard.gateway.config.AppConfig;
import com.ywu.standard.gateway.handler.HandlerInterface;
import com.ywu.standard.gateway.handler.header.impl.HeaderHandlerInterface;
import com.ywu.standard.gateway.handler.user.impl.UserHandlerInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Objects;

/**
 * @ClassName UserHandlerFilter
 * @Description 用户信息处理
 * @Author GroundDemo
 * @Date 2024/5/26 11:39
 * @Version 1.0
 **/
@Component
@Slf4j
public class UserHandlerFilter implements GlobalFilter, Ordered, HandlerInterface {
    @Autowired
    private List<UserHandlerInterface> userHandlerList;

    @Autowired
    private AppConfig appConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 人机接口走UserHandlerFilter  机机接口走UserMssaHandlerFilter
        if (isOpenService(exchange)) {
            return chain.filter(exchange);
        }
        // 校验开关是否开启
        if (!appConfig.getCheckTokenAndPermission()) {
            return chain.filter(exchange);
        }
        log.info("UserHandlerFilter start! userHandlerList size is {}", userHandlerList.size());
        // 判断是否需要拦截
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        for (UserHandlerInterface impl : userHandlerList) {
            Object handleRes = impl.handle(exchange);
            // 如果返回值为null，表明不需要校验拦截，直接放行
            if (Objects.isNull(handleRes)) {
                // 构建上下文，将放通状态设置到上下文中
                currentContext.setFilterChain(true);
                return chain.filter(exchange);
            }
            // 校验返回值是否为ServerWebExchange对象，如果不是，则构造返回体进行返回
            if (handleRes instanceof ServerWebExchange) {
                exchange = (ServerWebExchange) handleRes;
            } else {
                return generateResponseInfo(exchange, handleRes);
            }
        }
        log.info("UserHandlerFilter end!");
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 2;
    }
}
